package com.jake.data_structure_learning.quene;

public class MyCircularQueue {
    /**
     * 队列长度
     */
    private int length;

    private Integer[] objs;

    // 首
    private int head;

    // 尾
    private int tail;

    public int getNext(int value) {
        if (value < length - 1) {
            return ++value;
        } else {
            return 0;
        }
    }

    /** Initialize your data structure here. Set the size of the queue to be k. */
    /**
     * 构造器，设置队列长度为 k 。
     *
     * @param k
     */
    public MyCircularQueue(int k) {
        length = k;
        objs = new Integer[length];
        head = -1;
        tail = -1;
    }

    /** Insert an element into the circular queue. Return true if the operation is successful. */
    /**
     * 向循环队列插入一个元素。如果成功插入则返回真。
     *
     * @param value
     * @return
     */
    public boolean enQueue(int value) {
        if (this.isEmpty()) {
            tail = 0;
            head = 0;
            objs[0] = value;
            return true;
        } else if (this.isFull()) {
            return false;
        } else {
            objs[this.getNext(tail)] = value;
            tail = this.getNext(tail);
            return true;
        }
    }

    /** Delete an element from the circular queue. Return true if the operation is successful. */
    /**
     * 从循环队列中删除一个元素。如果成功删除则返回真。
     *
     * @return
     */
    public boolean deQueue() {
        if (this.isEmpty()) {
            return false;
        }
        // 如果当前是最后一个元素
        if (head == tail) {
            objs[head] = null;
            head = -1;
            tail = -1;
        } else {
            objs[head] = null;
            head = this.getNext(head);
        }
        return true;
    }

    /** Get the front item from the queue. */
    /**
     * 从队首获取元素。如果队列为空，返回 -1 。
     *
     * @return
     */
    public int Front() {
        if (this.isEmpty()) {
            return -1;
        } else {
//            int front=objs[head];
//            objs[head]=null;
//            head=this.getNext(head);
            return objs[head];
        }
    }

    /** Get the last item from the queue. */
    /**
     * 获取队尾元素。如果队列为空，返回 -1 。
     *
     * @return
     */
    public int Rear() {
        if (this.isEmpty()) {
            return -1;
        } else {
//            int rear=objs[tail];
//            objs[tail]=null;
//            tail=this.getNext(tail);
            return objs[tail];
        }
    }

    /** Checks whether the circular queue is empty or not. */
    /**
     * 检查循环队列是否为空。
     *
     * @return
     */
    public boolean isEmpty() {
        return head == -1 && tail == -1;
    }

    /** Checks whether the circular queue is full or not. */
    /**
     * 检查循环队列是否已满。
     *
     * @return
     */
    public boolean isFull() {
        return this.getNext(tail) == head;
    }
}
